<script>
	import store from './store'
	import token from './utils/token'
	export default {
		onLaunch: function() {
			//通过判断保存vuex数据持久化
			/* if (token.getToken('tokenTestHealth') != null) {
				if (store.state.userName === null) {
					store.dispatch('getUserInfo')
				}
			} */
			this.restoreUserInfo()
		},
		onShow: function() {
			this.routerInterceptor()
		},
		onHide: function() {
			console.log('App Hide')
		},
		methods: {
			//处理通过浏览器导航输入相关地址进行路由的拦截
			routerInterceptor() {
				// 获取当前页面路由
				let currentRoute;

				// H5环境下从window.location获取路由路径
				// #ifdef H5
				currentRoute = window.location.hash.replace(/^#\//, '').split('?')[0];
				// #endif

				// 非H5环境下使用getCurrentPages获取
				// #ifndef H5
				currentRoute = getCurrentPages().pop()?.route;
				// #endif
				console.log("当前路由:", currentRoute);

				// 白名单路由
				const whiteList = ['pages/index/index', 'index', 'pages/login/login',
					'pages/message/message', 'pages/mine/mine', 'pages/register/register',
					'pages/login/phone-login','pages/ai/aiDoc'
				];

				// 如果是undefined或空路由，默认放行（通常是首页）
				if (!currentRoute || currentRoute === '' || currentRoute === '/') {
					return;
				}

				// 统一处理路由格式（去除前后斜杠）
				const normalizedRoute = currentRoute.replace(/^\/+|\/+$/g, '');

				// 检查是否需要拦截
				if (!whiteList.includes(normalizedRoute) && !token.getToken()) {
					uni.showToast({
						title: '请先登录',
						icon: 'none',
						complete() {
							uni.redirectTo({
								url: '/pages/login/login'
							});
						}
					});
				}
			},
			//配置vuex持久化存储
			async restoreUserInfo() {
				if (token.getToken()) {
					const success = await store.dispatch('getUserInfo')
					if (!success) {
						uni.reLaunch({
							url: '/pages/login/login'
						})
					}
				}
			}
		}
	}
</script>

<style lang="scss">
	/*每个页面公共css */
	@import "uview-ui/index.scss";
</style>